<?php

namespace App\Models\Access\Permission;

use Illuminate\Database\Eloquent\Model;
use App\Models\Access\Permission\Traits\Relationship\PermissionRelationship;
use Illuminate\Support\Facades\DB;

/**
 * Class Permission
 * @package App\Models\Access\Permission
 */
class Permission extends Model
{
    use PermissionRelationship;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table='permissions';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'code', 'sort'];

    /**
     * @param array $attributes
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
    }

    /**
     * 插入记录
     * @param array $data
     * @return bool
     */
    public static function insertRow($data){

        if (empty($data))
            return false;

        return DB::table('permissions')->insert($data);

    }

    /**
     * 列表信息
     * @param string $where
     * @return array
     */
    public static function getList($fields='*',$limit=[0,1]){
        $r = [];
        $p = Permission::select($fields)->orderBy('sort','DESC')->where(['pid'=>0])->get()->toArray();
        foreach ($p as $item => $value){
            $r[] = $value;

            $t = Permission::select($fields)->orderBy('sort','DESC')->where(['pid'=>$value['id']])->get()->toArray();
            foreach ($t as $k => $v){
                $r[] = $v;
            }
        }
        return array_slice($r,$limit[0],$limit[1]);
    }

    /**
     * 记录数
     * @param array $where
     * @return integer
     */
    public static function getCount(){

        return DB::table('permissions')->count();

    }
    /**
     * 修改记录
     * @param array $where
     * @param array $data
     * @return bool
     */
    public static function updateRow($where,$data){

        if (empty($data))
            return false;

        return DB::table('permissions')
            ->where($where[0],$where['1'])
            ->update($data);

    }
    /**
     * 删除记录
     * @param array $where
     * @param array $data
     * @return bool
     */
    public static function deleteRow($where){
        if (empty($where))
            return false;

        return DB::table('permissions')
            ->where($where[0],$where[1])
            ->delete();

    }
    /**
     * 系统模块
     *
     * @return mixed
     */
    public static function getModular(){
        $where = ['pid'=>0];
        return DB::table('permissions')->where($where)->get();
    }

}
